<template>
<div>
  <div class="todo-container">
    <div class="todo-wrap">
     <Header :add="add"></Header>
     <List
         :todoList="todoList"
         :changeDone="changeDone"
         :deleteById="deleteById"
     >
     </List>
     <Footer
         :todoList="todoList"
         :deleteAllDone="deleteAllDone"
         :changeAllDone="changeAllDone"
     >
     </Footer>
    </div>
  </div>
</div>
</template>


<script>
import Header from "@/components/Header";
import List from "@/components/List";
import Footer from "@/components/Footer";
export default {
  name:"App",
  components: {Footer, List, Header},
  data(){
    return{
      todoList:[
        {id:"001",content:"篮球",done:false},
        {id:"002",content:"足球",done:false},
        {id:"003",content:"排球",done:false}
      ]
    }
  },
  methods:{
    //添加数据
    add(e){
      const content = e.target.value;
      if(content.length === 0 ){
        alert("请输入内容")
        return
      }
      if(this.todoList.find(v=>v.content === content)){
        alert("请勿输入重复内容")
        return;
      }
      const todoObj = {id:Math.random().toString(36).slice(2),content,done:false}
      this.todoList.unshift(todoObj)
      e.target.value = null;
    },
    //根据id来更改选中状态
    changeDone(id){
      this.todoList.map(v=>{
        if(v.id === id){
          v.done = !v.done
        }
        return v
      })
    },
    //根据Id删除某一项
    deleteById(id){
      this.todoList = this.todoList.filter(v=> v.id !== id)
    },
    //批量删除
    deleteAllDone(){
      this.todoList = this.todoList.filter(v=>{
        return !v.done
      })
    },
    //全选选中
    changeAllDone(newVal){
      this.todoList.map(v=>{
         v.done = newVal
        return v
      })
    }
  },
  //通过watch进行监听todoList,每次变化就将新的数据存储到本地空间
  watch:{
    todoList:{
        deep:true,
        handler(){
          localStorage.setItem("todoList",JSON.stringify(this.todoList))
        }
    }
  },
  //初始化结束,来获取本地存储的数据
  mounted() {
    this.todoList = JSON.parse(localStorage.getItem("todoList")|| "[]")
  }
}
</script>


<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}


/*app*/
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

</style>